package org.jeecg.common.util.xinyuan;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.*;

public class Utils {

    /**
     * post 获取生成加密后签名sign字符串
     * @param parameters
     * @param key
     * @return
     */
    public static String createSign(SortedMap<Object,Object> parameters, String key){
        StringBuffer sb = new StringBuffer();
        StringBuffer sbkey = new StringBuffer();
        Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if(null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
                sbkey.append(k + "=" + v + "&");
            }
        }
        //logger.info("字符串stringA:"+sb.toString());
        sbkey=sbkey.append(key);
        //logger.info("字符串stringSignTemp:"+sbkey.toString());
        //MD5加密,结果转换为小写字符
        String sign = MD5Util.getMd5Code(sbkey.toString()).toLowerCase();
        return sign;
    }
    //验签
    public static boolean checkSign(JSONObject jsobj, String secret_key){
        Map<String, String> params = JSONObject.parseObject(jsobj.toJSONString(), new TypeReference<Map<String, String>>(){});

        String sign = jsobj.getString("sign");

        params.remove("sign");

        TreeMap map = new TreeMap();
        map.putAll(params);

        String sign2 = Utils.createSign(map,secret_key);
        if(sign.equals(sign2)){
            return true;
        }
        return false;
    }
}
